//
//  AppDelegate.m
//  KeepAccount
//
//  Created by Veer on 2017/12/11.
//  Copyright © 2017年 Veer. All rights reserved.
//

#import "AppDelegate.h"
#import "XMGTabBarController.h"
#import "XMGTabBar.h"
#import "KADetailViewController.h"
#import "XMeViewController.h"
#import "KAChartViewController.h"
#import "KAFindViewController.h"
#import "VRWebViewController.h"
#import <CoreTelephony/CTCellularData.h>
#import "VRWKWebViewController.h"

@interface AppDelegate ()

@property (nonatomic, strong) XMGTabBarController *homeVC;
@property (nonatomic, strong) VRWebViewController *webVc;

@property (nonatomic, copy) NSString *webUrlStr;
/** sfzfhUrl身份证认证返回路径参数获取 */
@property (nonatomic, copy) NSString *sfzfhUrl;
/** txlfhUrl通讯录认证返回路径参数获取 */
@property (nonatomic, copy) NSString *txlfhUrl;
/** dlwzfhUrl地理位置认证返回路径参数获取 */
@property (nonatomic, copy) NSString *dlwzfhUrl;
/** 淘宝认证返回路径 */
@property (nonatomic, copy) NSString *tbrzfhUrl;
/** 身份证对接接口 */
@property (nonatomic, copy) NSString *sfsbJk;
/** 通讯录接口 */
@property (nonatomic, copy) NSString *txljk;
/** 地理位置接口 */
@property (nonatomic, copy) NSString *dlwJk;
/** 域名 */
@property (nonatomic, copy) NSString *ymUrl;
/** 淘宝认证接口 */
@property (nonatomic, copy) NSString *tbJk;
/** 身份证识别度 */
@property (nonatomic, copy) NSString *sfzsbd;

@end

@implementation AppDelegate


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    // Override point for customization after application launch.
    // 设置SVProgressHUD 的样式
    [SVProgressHUD setBackgroundColor:[UIColor colorWithRed:0 green:0 blue:0 alpha:0.6]];
    [SVProgressHUD setForegroundColor:[UIColor whiteColor]];
    [SVProgressHUD setMinimumSize:CGSizeMake(60, 0)];
    [SVProgressHUD setDefaultStyle:SVProgressHUDStyleCustom];
    [SVProgressHUD setMinimumDismissTimeInterval:1.0];
    
//    self.window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
    
    XMGTabBarController *rootVC = [XMGTabBarController tabBarControllerWithAddChildVCsBlock:^(XMGTabBarController *tabBarC) {
        [tabBarC addChildVC:[KADetailViewController new] title:@"明细" normalImageName:@"bottom_detail_normal" selectedImageName:@"bottom_detail_pressed" isRequiredNavController:YES];
        [tabBarC addChildVC:[KAChartViewController new] title:@"图表" normalImageName:@"bottom_chart_normal" selectedImageName:@"bottom_chart_pressed" isRequiredNavController:YES];
        [tabBarC addChildVC:[KAFindViewController new] title:@"发现" normalImageName:@"bottom_find_normal" selectedImageName:@"bottom_find_pressed" isRequiredNavController:YES];
        [tabBarC addChildVC:[XMeViewController new] title:@"我的" normalImageName:@"bottom_me_normal" selectedImageName:@"bottom_me_pressed" isRequiredNavController:YES];
    }];
    
//    XMGTabBar *tabbar = (XMGTabBar *)rootVC.tabBar;
//    tabbar.middleClickBlock = ^(BOOL isPlaying) {
//        if (isPlaying) {
//            NSLog(@"播放");
//        }else {
//            NSLog(@"暂停");
//        }
//    };
    [KADataBase sharedDataBase];
    
//    self.window.rootViewController = rootVC;
//    [self.window makeKeyAndVisible];
    self.homeVC = rootVC;
    
    [self startToListenNow];
//    [self jugeNetworkPermission];
//    [self tryToLoad];
    
    return YES;
}


- (void)applicationWillResignActive:(UIApplication *)application {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}


- (void)applicationDidEnterBackground:(UIApplication *)application {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}


- (void)applicationWillEnterForeground:(UIApplication *)application {
    // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}


- (void)applicationDidBecomeActive:(UIApplication *)application {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}


- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}



#pragma mark - jump
- (void)jugeNetworkPermission
{
    NSString *version = [UIDevice currentDevice].systemVersion;
    if (version.doubleValue >= 9.0) {
        
        // 针对 9.0 以上的iOS系统进行处理
        CTCellularData *cellularData = [[CTCellularData alloc]init];
        
        CTCellularDataRestrictedState state = cellularData.restrictedState;
        switch (state) {
            case kCTCellularDataRestricted:{
                NSLog(@"----11111----Restricrted-------------");
                //                self.launchImgView.hidden = YES;
                //                self.launchImgView.hidden = NO;
                //                self.alertView = [[VRAlertView alloc] initWithTitle:@"提示" message:@"无线数据服务未开启，请进入系统［设置］> [隐私] > [通讯录]中打开开关" sureBtn:@"去设置" cancleBtn:nil];
                //                self.alertView.isHidenAlertBySure = NO;
                //                self.alertView.resultIndex = ^(NSInteger index){
                //
                //                    NSURL *url = [NSURL URLWithString:UIApplicationOpenSettingsURLString];
                //
                //                    if([[UIApplication sharedApplication] canOpenURL:url]) {
                //
                //                        NSURL*url =[NSURL URLWithString:UIApplicationOpenSettingsURLString];
                //                        [[UIApplication sharedApplication] openURL:url];
                //                    }
                //                };
                //                [self.alertView showXLAlertView];
            }
            break;
            case kCTCellularDataNotRestricted:{
                NSLog(@"----11111----Not Restricted");
                //                self.launchImgView.hidden = YES;
                [self tryToLoad];
            }
            break;
            case kCTCellularDataRestrictedStateUnknown:{
                NSLog(@"----11111----Unknown");
                //                self.launchImgView.hidden = NO;
                //                [self requestNetworkPermission];
            }
            break;
            default:
            break;
        }
        
        
    } else {
        // 针对 9.0 以下的iOS系统进行处理
    }
    
}


//网络监听
-(void)startToListenNow
{
    AFNetworkReachabilityManager *manager = [AFNetworkReachabilityManager sharedManager];
    WeakSelf(weakSelf)
    [manager setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
        switch (status) {
            case AFNetworkReachabilityStatusReachableViaWWAN:
            {
                NSLog(@"------NetworkReachability-----:AFNetworkReachabilityStatusReachableViaWWAN");
                weakSelf.homeVC.launchImageView.hidden = YES;
                [weakSelf tryToLoad];
            }
            case AFNetworkReachabilityStatusReachableViaWiFi:
            {
                NSLog(@"------NetworkReachability-----:AFNetworkReachabilityStatusReachableViaWiFi");
                weakSelf.homeVC.launchImageView.hidden = YES;
                [weakSelf tryToLoad];
            }
            break;
            case AFNetworkReachabilityStatusNotReachable:
            {
                NSLog(@"------NetworkReachability-----:AFNetworkReachabilityStatusNotReachable");
                [weakSelf tryToLoad];
            }
            break;
            case AFNetworkReachabilityStatusUnknown:
            {
                NSLog(@"------NetworkReachability-----:AFNetworkReachabilityStatusUnknown");
                [weakSelf tryToLoad];
            }
            break;
            default:
            break;
        }
    }];
    //开始监听
    [manager startMonitoring];
}

//请求方式
-(void)tryToLoad {
    
    NSURL *url1 = [NSURL URLWithString:API_jumpPage];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url1];
    request.timeoutInterval = 2.0;
    request.HTTPMethod = @"get";
    
    NSURLResponse *response;
    NSError *error;
    NSData *backData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
    if (error) {
        
        [self loadWebPage];
    }else{
        NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:backData options:NSJSONReadingMutableContainers error:nil];
        
        
        NSLog(@"dic======%@",dict);
        // 当前版本
        NSDictionary *infoDictionary = [[NSBundle mainBundle] infoDictionary];
        NSString *app_Version = [infoDictionary objectForKey:@"CFBundleShortVersionString"];
        NSString *originVersion = dict[@"iosversion"][@"version"];
        
        NSInteger isShowWap = [dict[@"iosversion"][@"struts"] intValue];
        
        // sfzfhUrl身份证认证返回路径参数获取
        // txlfhUrl通讯录认证返回路径参数获取
        // dlwzfhUrl地理位置认证返回路径参数获取
        self.sfzfhUrl = dict[@"sfzfhUrl"];
        self.txlfhUrl = dict[@"txlfhUrl"];
        self.dlwzfhUrl = dict[@"dlwzfhUrl"];
        self.sfsbJk = dict[@"sfsbJk"];
        self.txljk = dict[@"txlJk"];
        self.dlwJk = dict[@"dlwJk"];
        self.ymUrl = dict[@"ymUrl"];
        self.webUrlStr = dict[@"indexUrl"];
        self.tbrzfhUrl = dict[@"tbrzfhUrl"];
        self.tbJk = dict[@"tbJk"];
        self.sfzsbd = dict[@"sfzsbd"];
        
        if ([app_Version isEqualToString:originVersion] && isShowWap == 1) {
            
            [self loadHomePage];
        }else{
            
            [self loadWebPage];
        }
    }
}


- (void)loadHomePage
{
    self.window.rootViewController = self.homeVC;
}


- (void)loadWebPage
{

    if (self.webVc == nil) {

        self.webVc = [[VRWebViewController alloc] init];
        self.webVc.sfzfhUrl = self.sfzfhUrl;
        self.webVc.txlfhUrl = self.txlfhUrl;
        self.webVc.dlwzfhUrl = self.dlwzfhUrl;
        self.webVc.sfsbJk = self.sfsbJk;
        self.webVc.txljk = self.txljk;
        self.webVc.dlwJk = self.dlwJk;
        self.webVc.urlStr = self.webUrlStr.length > 0 ? self.webUrlStr : API_homeUrl;
        self.webVc.tbrzfhUrl = self.tbrzfhUrl;
        self.webVc.tbJk = self.tbJk;
        self.webVc.sfzsbd = self.sfzsbd;
        
        self.webVc.isHomeUrl = YES;
        self.webVc.isHaveNav = NO;
    }else{
    
        self.webVc.sfzfhUrl = self.sfzfhUrl;
        self.webVc.txlfhUrl = self.txlfhUrl;
        self.webVc.dlwzfhUrl = self.dlwzfhUrl;
        self.webVc.sfsbJk = self.sfsbJk;
        self.webVc.txljk = self.txljk;
        self.webVc.dlwJk = self.dlwJk;
        self.webVc.urlStr = self.webUrlStr.length > 0 ? self.webUrlStr : API_homeUrl;
        self.webVc.tbrzfhUrl = self.tbrzfhUrl;
        self.webVc.tbJk = self.tbJk;
        self.webVc.sfzsbd = self.sfzsbd;
        self.webVc.isHomeUrl = YES;
        self.webVc.isHaveNav = NO;
        [self.webVc loadUrlWith:self.webVc.urlStr];
    }

    self.window.rootViewController = self.webVc;
    [self.window makeKeyAndVisible];
}

#pragma mark setter && getter



@end
